import {
  createRouter,
  createWebHashHistory,
  RouteRecordRaw,
  createWebHistory,
} from 'vue-router'
import { nextTick } from 'vue'
import Cookies from 'js-cookie'
import store from '@/store'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/login', // 重定向
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login/Login.vue'),
    meta: {
      isLogin: true,
    },
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/Home/Home.vue'),
  },
  // {
  //   path: '/ums',
  //   name: 'Ums',
  //   component: () => import('../views/Home/Home.vue'),
  //   children: [
  //     {
  //       path: 'admin',
  //       name: 'Admin',
  //       component: () => import('@/views/Ums/Admin.vue'),
  //     },
  //   ],
  // },
]

const router = createRouter({
  // createWebHistory：history模式。createWebHashHistory：hash模式
  history: createWebHistory(),
  routes,
})

router.beforeEach((to, from, next) => {
  const token = Cookies.get('token')
  if (to.meta.isLogin) {
    next()
  } else {
    if (token) {
      // 动态生成路由
      const menus = store.getters.getNewMenus
      let newRouter: any = {}
      // 循环菜单对象
      for (let key in menus) {
        newRouter = {
          path: '/' + menus[key].name,
          name: menus[key].name,
          component: () => import('../views/Home/Home.vue'),
          // redirect: '/' + menus[key].name + '/' + menus[key].children[0].name,
          children: [],
        }
        // 循环 children数组
        for (let i = 0; i < menus[key].children.length; i++) {
          newRouter.children.push({
            path: menus[key].children[i].name,
            name: menus[key].children[i].name,
            component: () =>
              import(
                `../views/${menus[key].name}/${menus[key].children[i].name}.vue`
              ),
          })
        }
        // 动态添加路由规则，使用addRoute方法
        router.addRoute(newRouter)
      }
      next()
    } else {
      next('/login')
    }
  }
})

// export const initRouter = (app: App<Element>) => {
//   app.use(router)
// }

export default router
